/*
 * Copyright 2011 group coding kata nantes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package fr.coding.kata.nantes.bowling.sylvain;

/**
 * Utility class for Bowling game.
 *
 * @author Sylvain Leduby
 * @since 1.0
 */
public class BowlingUtil {

    /**
     * Conversion array from integer score to character representation of this score.
     */
    private static final char[] SCORE_TO_CHAR = "-123456789X".toCharArray();

    /**
     * Conversion array from character representation of a score to its integer value.
     */
    private static final int[] CHAR_TO_SCORE;

    static {
        CHAR_TO_SCORE = new int[89];
        for (int i = 0; i < 89; i++) {
            CHAR_TO_SCORE[i] = 0; // default to 0
        }
        for (int i = 1; i < 10; i++) {
            CHAR_TO_SCORE[48 + i] = i; // '1' to '9'
        }
        CHAR_TO_SCORE[88] = 10; // 'X'
    }

    /**
     * Private constructor.
     */
    private BowlingUtil() {
        super();
    }

    /**
     * Convert an integer value to corresponding try character:
     * <p/>
     * <pre>
     * 0: '-'
     * 1: '1'
     * 2: '2'
     * ...
     * 9: '9'
     * 10: 'X'
     * </pre>
     *
     * @param value An integer from 0 to 10.
     * @return The corresponding character representation of {@code value} for a "try".
     */
    public static char toRoll(final int value) {
        return SCORE_TO_CHAR[value];
    }

    /**
     * Get the integer value from the character representation of a try.
     *
     * @param aTry The score of a single try.
     * @return The integer value from the character representation of the score of a single try.
     */
    public static int toScore(final char aTry) {
        return CHAR_TO_SCORE[aTry];
    }

    /**
     * Converts an array of integer representing the scores of tries to a String.
     * <p/>
     * Examples:
     * <p/>
     * <pre>
     * [0, 1, 2, 5, 8, 1, 9, 0]: "-125819-"
     * </pre>
     *
     * @param tries
     * @return
     */
    public static String toLine(final int... tries) {
        String roll = "";
        if (tries != null) {
            final int length = tries.length;
            if (length > 0) {
                final char[] tmp = new char[length];
                for (int i = 0; i < length; i++) {
                    tmp[i] = toRoll(tries[i]);
                }
                roll = String.valueOf(tmp);
            }
        }
        return roll;
    }

}
